import { Inject, Injectable } from '@nestjs/common';
import { IClientPublishOptions, MqttClient, Packet } from 'mqtt';
import { MQTT_PUBLISH_CLIENT_PROVIDER } from '../constants/mqtt.constant';

@Injectable()
export class MqttPublishService {
  constructor(
    @Inject(MQTT_PUBLISH_CLIENT_PROVIDER)
    private readonly mqttPublishClient: MqttClient
  ) {}

  /**
   * 发布mqtt消息
   * @param topic 发布主题
   * @param message 发布内容
   * @param options 附加参数
   * @returns 发布结果
   */
  publish(topic: string, message: any, options?: IClientPublishOptions): Promise<{ success: boolean; error?: Error; packet?: Packet }> {
    if (!(typeof message === 'string') && !(message instanceof Buffer)) {
      message = JSON.stringify(message); // 如果message不是string类型，也不是Buffer类型，就将其序列化
    }

    return new Promise(resolve => this.mqttPublishClient.publish(topic, message, options, (error, packet) => resolve({ success: !!!error, error, packet })));
  }

  /**
   * 删除Retain消息
   * @param topic Retain 主题
   * @returns 删除结果
   */
  removeRetainTopic(topic: string): Promise<{ success: boolean; error?: Error; packet?: Packet }> {
    return new Promise(resolve => this.mqttPublishClient.publish(topic, '', (error, packet) => resolve({ success: !!!error, error, packet })));
  }
}
